import java.io.File;
import java.util.logging.Logger;

import com.usoft.grpc.example.helloworld.GreeterGrpc;

import io.grpc.Server;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NettyServerBuilder;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.ServerChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;

/**
 * Created by xinxingegeya on 15/9/25.
 */
public class GreeterServer {

    private static final Logger logger = Logger
        .getLogger(GreeterServer.class.getName());

    /* The port on which the server should run */
    private int port = 8888;
    private Server server;

    private void start() throws Exception {

        File cert = Utils.loadCert("www.helloworld.com.cert.pem");
        File key = Utils.loadCert("www.helloworld.com.key.pkcs8.pem");

        SslContextBuilder sslContextBuilder = GrpcSslContexts.forServer(cert,
            key);

        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder,
            SslProvider.OPENSSL);
        final EventLoopGroup boss = new NioEventLoopGroup();
        final EventLoopGroup worker = new NioEventLoopGroup();
        final Class<? extends ServerChannel> channelType = NioServerSocketChannel.class;

        server = NettyServerBuilder.forPort(port).bossEventLoopGroup(boss)
            .workerEventLoopGroup(worker).channelType(channelType)
            .addService(GreeterGrpc.bindService(new HelloWorldServiceImpl()))
            .sslContext(sslContextBuilder.build()).build().start();

        logger.info("Server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println(
                    "*** shutting down gRPC server since JVM is shutting down");
                GreeterServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon
     * threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws Exception {
        final GreeterServer searchServer = new GreeterServer();
        searchServer.start();
        searchServer.blockUntilShutdown();
    }
}
